import { useCallback, useState } from 'react'
import { IMaterialResponse } from '../inteface/product-info'

interface CustomizedSubCategory {
  id: number
  title: string
  material: {
    id: number
    name: string
    price: number
  }
}

interface CustomizedMaterial {
  categoryName: string
  subCategories: CustomizedSubCategory[]
}

interface CustomizedMaterials {
  [categoryId: string]: CustomizedMaterial
}

interface SelectedCustomization {
  [materialName: string]: {
    categoryId: number
    materialId: number
  }
}

interface UseCustomizationReturn {
  customizedMaterials: CustomizedMaterials
  selectedCustomization: SelectedCustomization
  processCustomization: (
    materialData: IMaterialResponse | undefined,
    categoryKey: string,
    formData: { [key: string]: number },
  ) => void
}

/**
 * useCustomization Hook
 *
 * 管理材料定制状态和逻辑，包括：
 * 1. 保存用户定制的材料详情（用于费用计算）
 * 2. 保存用户选择的材料 ID（用于 API 提交）
 * 3. 处理定制数据的转换和保存
 *
 * @returns 定制材料状态和处理函数
 */
export const useCustomization = (): UseCustomizationReturn => {
  // 保存用户定制的材料详细信息（用于费用计算）
  const [customizedMaterials, setCustomizedMaterials] = useState<CustomizedMaterials>({})

  // 保存用户选择的材料（用于 API 提交）
  const [selectedCustomization, setSelectedCustomization] = useState<SelectedCustomization>({})

  /**
   * 处理定制提交
   * 提取用户选择的材料信息，分别保存用于费用展示和 API 提交
   */
  const processCustomization = useCallback(
    (
      materialData: IMaterialResponse | undefined,
      categoryKey: string,
      formData: { [key: string]: number },
    ) => {
      if (!materialData || !categoryKey) return

      const categoryId = Number(categoryKey)
      const categoryName = materialData.categories.categoryName
      const subCategories: CustomizedSubCategory[] = []
      const newSelectedCustomization: SelectedCustomization = {}

      // 遍历所有子类别，提取用户选择的材料信息
      materialData.categories.subCategories.forEach((subCategory) => {
        const selectedMaterialId = formData[subCategory.id + '']
        if (!selectedMaterialId) return

        // 找到对应的材料
        const material = subCategory.materials?.find((m) => m.id === selectedMaterialId)
        if (!material) return

        // 保存用于费用展示
        subCategories.push({
          id: subCategory.id,
          title: subCategory.title,
          material: {
            id: material.id,
            name: material.name,
            price: material.price,
          },
        })

        // 保存用于 API 提交
        newSelectedCustomization[material.name] = {
          categoryId,
          materialId: material.id,
        }
      })

      // 更新定制材料数据（用于费用计算）
      setCustomizedMaterials((prev) => ({
        ...prev,
        [categoryId]: {
          categoryName,
          subCategories,
        },
      }))

      // 更新选择的材料（用于 API 提交）
      setSelectedCustomization((prev) => ({
        ...prev,
        ...newSelectedCustomization,
      }))
    },
    [],
  )

  return {
    customizedMaterials,
    selectedCustomization,
    processCustomization,
  }
}

